<template>
	<div class="group">
		<el-tabs v-model="activeName" @tab-click="handleClick">
			<el-tab-pane label="分组管理" name="group">
				<div class="tips">
					<!-- 创建分组 的组件 -->
					<AddGroup
						:showAddGroup="showAddGroup"
						:addGropusData="addGropusData"
						@getAddProps="getAddProps"
						@changeProp="changeProp"
						@addRules="addRules"
						@cancelAddGroup="cancelAddGroup"
						@removeRules="removeRules"
						@cancelCustomProp="cancelCustomProp"
					/>
					<!-- 导入分组 -->
					<ImportGroups
						v-show="showImportGroups"
						:show="showImportGroups"
						@close="
							() => {
								showImportGroups = false;
							}
						"
						@importGroupsSuccess="() => {
							this.initGroupList();
							this.showImportGroups = false;
						}"
					/>
					<!-- 编辑分组名称组件 -->
					<EditGroup :showEditTips="showEditTips" :editGroupData="editGroupData" @cancelEditGroup="cancelEditGroup" @getEditGroupName="getEditGroupName" />
					<!-- 绑定工作时间组件 -->
					<BindGroupWorkingTime
						:showBindGroupWorkTime="showBindGroupWorkTime"
						:workingTimeData="workingTimeData"
						@closeBindGroupWorkTime="closeBindGroupWorkTime"
						@changePageSizeWorkingTime="changePageSizeWorkingTime"
						@changeCurrentPageWorkingTime="changeCurrentPageWorkingTime"
						@apply="apply"
						ref="bindWorkTime"
					/>
					<!-- 绑定工作时日组件 -->
					<BindGroupWorkingDays
						:showBindGroupWorkDayView="showBindGroupWorkDayView"
						:selectWorkingDaysList="selectWorkingDaysList"
						:tableData="tableData"
						@closeBindGroupWorkDays="closeBindGroupWorkDays"
						@applyWithWorkDays="applyWithWorkDays"
						@currentWorkingDay="currentWorkingDay"
						@changePageSizeWithWorkingDays="changePageSizeWithWorkingDays"
						@changeCurrentPageWithWorkingDays="changeCurrentPageWithWorkingDays"
						ref="bindWorkDay"
					/>
				</div>
				<div class="head">
					<el-button type="primary" @click="addGroupName">创建分组</el-button>
					<el-button type="primary" @click="() => {this.showImportGroups = true;}">导入分组</el-button>
				</div>
				<div class="table">
					<Table :tableData="groupsData">
						<template v-slot:btn>
							<el-table-column width="800px" align="center" label="操作">
								<template slot-scope="scope">
									<el-button size="mini" type="primary" @click="editGroup(scope.$index, scope.row)">编辑</el-button>
									<el-button size="mini" type="primary" @click="showSelectWorkdayView(scope.$index, scope.row)">绑定工作日规则</el-button>
									<el-button size="mini" type="primary" @click="bindGroupWorkTime(scope.$index, scope.row)">绑定工作时间</el-button>
									<el-button size="mini" type="danger" @click="deleteGroup(scope.$index, scope.row)">删除</el-button>
								</template>
							</el-table-column>
						</template>
					</Table>
				</div>
				<br />
				<div class="page">
					<PageSize :pages="checkData" @changePageSize="changePageSize" @changeCurrentPage="changeCurrentPage" />
				</div>
			</el-tab-pane>
		</el-tabs>
	</div>
</template>

<script>
import { getGroupsList, addGroups, deleteGroups, updateGroups, bindGroupWorkingTime, getWorkingTimeList, getWorkingDaysList } from '../../api/api';
import Table from '../components/Table.vue';
import PageSize from '../components/PageSize.vue';
import AddGroup from './AddGroup.vue';
import EditGroup from './EditGroup.vue';
import BindGroupWorkingTime from './BindGroupWorkingTime.vue';
import BindGroupWorkingDays from './BindGroupWorkingDays.vue';
import ImportGroups from './ImportGroups.vue';

import { validateGroupName } from '@/utils/formValidate';

export default {
	components: {
		Table,
		PageSize,
		AddGroup,
		EditGroup,
		BindGroupWorkingTime,
		BindGroupWorkingDays,
		ImportGroups
	},
	data() {
		return {
			// 新增分组数据
			showAddGroup: false,
			showImportGroups: false,
			addGropusData: {
				name: '',
				customizedPolicy: [],
				defaultPolicy: 'least-used',
				rulesProp: [],
				customAttributes: [],
				groupNameRules: [
					{ required: true, message: '请填写分组名称', trigger: ['change', 'blur'] },
					{ validator: validateGroupName, trigger: ['blur', 'change'] }
				],
				groupWorkRules: [{ required: true, message: '请选择派工规则', trigger: ['change'] }]
			},

			// 编辑分组数据
			showEditTips: false,
			editGroupData: {
				groupName: '',
				groupId: '',
				index: '',
				groupNameRules: [
					{ required: true, message: '请填写分组名称', trigger: ['change', 'blur'] },
					{ validator: validateGroupName, trigger: ['blur', 'change'] }
				]
			},
			// 分组管理表格数据
			groupsData: {
				sort: false,
				tableHead: [
					{
						label: '名称',
						prop: 'groupName'
					}
				],
				tableConent: [],
				showIndex: false
			},
			checkData: {
				page: 1,
				pageSize: 10,
				total: 0
			},
			activeName: 'group',
			groupName: '',
			//绑定工作日列表数据
			showBindGroupWorkDayView: false,
			selectWorkingDaysList: {
				name: '',
				startTime: '',
				endTime: '',
				username: '',
				pages: { page: 1, pageSize: 10, total: 0 }
			},
			tableData: {
				sort: false,
				tableHead: [
					{
						label: '规则名称',
						prop: 'name'
					},
					{
						label: '创建时间',
						prop: 'createdAt'
					},
					{
						label: '创建人ID',
						prop: 'userName'
					}
				],
				tableConent: [], //工作日列表数据
				showIndex: true,
				showCheck: true
			},

			//绑定工作时间数据
			showBindGroupWorkTime: false,
			workingTimeData: {
				sort: false,
				tableHead: [
					{
						label: '规则名称',
						prop: 'workTimeName'
					},
					{
						label: '创建时间',
						prop: 'createdAt'
					},
					{
						label: '创建人ID',
						prop: 'userName'
					}
				],
				groupId: '',
				tableConent: [],
				showIndex: true,
				showCheck: true,
				checkData: {
					page: 1,
					pageSize: 10,
					total: 0
				}
			},
			selectWorkTimeId: null,
			selectWorkDayitemId: null
		};
	},

	mounted() {
		this.initGroupList();
	},
	methods: {
		//绑定工作日弹窗按钮
		showSelectWorkdayView(index, row) {
			this.editGroupData.groupId = row.groupId;
			this.selectWorkDayitemId = this.groupsData.tableConent[index].groupWorkTime.workDayId;
			this.getWorkingDaysList();
		},
		//分页工作日
		changeCurrentPageWithWorkingDays(val) {
			this.selectWorkingDaysList.pages.page = val;
			this.selectWorkingDaysList.pages.pageSize = 10;
			this.getWorkingDaysList();
		},
		//分页工作日
		changePageSizeWithWorkingDays(val) {
			this.selectWorkingDaysList.pages.pageSize = val;
			this.selectWorkingDaysList.pages.page = 1;
			this.getWorkingDaysList();
		},

		//关闭绑定工作日弹窗
		closeBindGroupWorkDays() {
			this.showBindGroupWorkDayView = false;
		},
		//分组绑定工作日规则 selectWorkDayitemId：工作日规则id
		applyWithWorkDays(selectWorkDayitemId) {
			let array = [{ op: 'replace', path: 'workDayId', value: selectWorkDayitemId }];
			let data = { id: this.editGroupData.groupId, workTimes: array };
			if (this.$refs.bindWorkDay.$refs.tableEle.$refs.singleTable.selection.length === 0) {
				this.$message.error('请选择工作日');
				return;
			}
			bindGroupWorkingTime(data)
				.then(() => {
					this.$message.success('应用成功！');
					this.showBindGroupWorkDayView = false;
					this.initGroupList();
				})
				.catch(() => {
					this.$message.error('应用失败');
				});
		},
		//工作日列表数据
		getWorkingDaysList() {
			let workingDaysData = {
				page: this.selectWorkingDaysList.pages.page,
				pageSize: this.selectWorkingDaysList.pages.pageSize,
				name: '',
				startTime: '',
				endTime: '',
				username: ''
			};
			getWorkingDaysList(workingDaysData)
				.then(res => {
					console.log(res);
					if (res.status === 200) {
						this.selectWorkingDaysList.pages.total = res.data.result.count;
						this.tableData.tableConent = res.data.result.rows.map(item => {
							return {
								id: item.id,
								name: item.name,
								createdAt: this.$moment(item.createdAt).format('YYYY-MM-DD HH:mm:ss'),
								userName: item.user && item.user.userName ? item.user.userName : '-'
							};
						});
						this.showBindGroupWorkDayView = true;
					} else {
						this.$message.error('获取工作日列表失败');
					}
				})
				.then(() => {
					this.$nextTick(() => {
						this.$refs.bindWorkDay.$refs.tableEle.$refs.singleTable.clearSelection();
						this.tableData.tableConent.forEach(item => {
							// console.warn('getWorkingDaysList:', item);
							if (this.selectWorkDayitemId === item.id) {
								this.$refs.bindWorkDay.$refs.tableEle.$refs.singleTable.toggleRowSelection(item, true);
							}
						});
					});
				})
				.catch(() => {
					this.$message.error('获取工作日列表失败');
				});
		},
		// 绑定工作时间相关方法
		bindGroupWorkTime(index, row) {
			this.editGroupData.groupId = row.groupId;
			this.selectWorkTimeId = this.groupsData.tableConent[index].groupWorkTime.workTimeId;
			this.getWorkingTimeInit();
		},
		// 工作时间列表
		getWorkingTimeInit() {
			let data = {
				page: this.workingTimeData.checkData.page,
				pageSize: this.workingTimeData.checkData.pageSize,
				name: '',
				startTime: '',
				endTime: '',
				username: ''
			};
			getWorkingTimeList(data)
				.then(res => {
					if (res.status === 200) {
						this.workingTimeData.checkData.total = res.data.result.count;
						this.workingTimeData.tableConent = res.data.result.rows.map(item => {
							return {
								workTimeId: item.id,
								workTimeName: item.name,
								createdAt: this.$moment(item.createdAt).format('YYYY-MM-DD HH:mm:ss'),
								userName: item.user && item.user.userName ? item.user.userName : '-'
							};
						});
						this.showBindGroupWorkTime = true;
					}
				})
				.then(() => {
					this.$nextTick(() => {
						this.$refs.bindWorkTime.$refs.tableEle.$refs.singleTable.clearSelection();
						this.workingTimeData.tableConent.forEach(item => {
							if (this.selectWorkTimeId === item.workTimeId) {
								this.$refs.bindWorkTime.$refs.tableEle.$refs.singleTable.toggleRowSelection(item, true);
							}
						});
					});
				})
				.catch(() => {
					this.$message.error('获取工作时间列表失败');
				});
		},
		// 应用工作时间
		apply(selectWorkTimeId) {
			let array = [{ op: 'replace', path: 'workTimeId', value: selectWorkTimeId }];
			let data = { id: this.editGroupData.groupId, workTimes: array };
			if (this.$refs.bindWorkTime.$refs.tableEle.$refs.singleTable.selection.length === 0) {
				this.$message.error('请选择工作时间');
				return;
			}
			bindGroupWorkingTime(data)
				.then(() => {
					this.$message.success('应用成功！');
					this.showBindGroupWorkTime = false;
					this.initGroupList();
				})
				.catch(() => {
					this.$message.error('应用失败！');
				});
		},
		closeBindGroupWorkTime() {
			this.showBindGroupWorkTime = false;
		},
		changePageSizeWorkingTime(val) {
			this.workingTimeData.checkData.pageSize = val;
			this.workingTimeData.checkData.page = 1;
			this.getWorkingTimeInit();
		},
		changeCurrentPageWorkingTime(val) {
			this.workingTimeData.checkData.page = val;
			this.workingTimeData.checkData.pageSize = 10;
			this.getWorkingTimeInit();
		},
		//分组列表初始化
		initGroupList() {
			getGroupsList(this.checkData)
				.then(res => {
					if (res.status === 200) {
						const total = res.data.count;
						this.checkData.total = total;
						const { data } = res.data;
						console.log(data, 'groupList');
						this.groupsData.tableConent = data.map(item => {
							return {
								groupId: item.id,
								groupName: item.name,
								groupWorkTime: item.groupWorkTime
							};
						});
					}
				})
				.catch(err => {
					this.$requestApiError(err, () => {
						this.$router.push('/');
					});
				});
		},
		// 增加分组相关方法
		addRules() {
			this.addGropusData.customizedPolicy.push({ name: '', weight: 0, attribute: '', rules: [] });
		},
		removeRules(index) {
			this.addGropusData.customizedPolicy.splice(index, 1);
		},
		addGroupName() {
			this.addGropusData.name = '';
			this.addGropusData.customizedPolicy = [];
			this.addGropusData.defaultPolicy = 'least-used';
			this.addGropusData.rulesProp = [];
			this.addGropusData.customAttributes = [];
			this.showAddGroup = true;
		},
		cancelAddGroup() {
			this.showAddGroup = false;
		},
		getAddProps(groupData) {
			let data = {};
			let customizedPolicy = groupData.customizedPolicy;
			let customizedPolicyData = [];
			if (customizedPolicy.length > 0) {
				for (let index = 0; index < customizedPolicy.length; index++) {
					let policy = customizedPolicy[index];
					if (!policy.name || !policy.attribute || !policy.rules) {
						this.$message.error('请填写完整信息');
						return;
					}
					if (policy.rules === 'customized' && !policy.customizedRules) {
						this.$message.error('请填写完整信息');
						return;
					}
					let item = { name: policy.name, weight: policy.weight, attribute: policy.attribute, rules: policy.rules };
					if (policy.rules === 'customized') {
						item.rules = policy.customizedRules.split(',');
					}
					customizedPolicyData.push(item);
				}
			}
			data.customizedPolicy = customizedPolicyData;
			data.defaultPolicy = groupData.defaultPolicy;
			data.name = groupData.name;
			addGroups(data)
				.then(res => {
					if (res.status === 200) {
						this.$message.success('新增分组成功！');
						this.cancelAddGroup();
						this.initGroupList();
					}
				})
				.catch(err => {
					this.$Spin.hide();
					if (err.code === '1002') {
						this.$message.error('新增分组失败，分组已存在！');
					} else {
						this.$message.error('新增分组失败!');
					}
					this.initGroupList();
				});
			this.showAddGroup = false;
		},
		// 编辑分组相关方法
		editGroup(index, row) {
			this.showEditTips = true;
			this.editGroupData.groupName = row.groupName;
			this.editGroupData.groupId = row.groupId;
		},
		cancelEditGroup() {
			this.showEditTips = false;
		},
		getEditGroupName(groupData) {
			let data = {};
			data.id = groupData.groupId;
			data.name = groupData.groupName;
			updateGroups(data)
				.then(res => {
					if (res.status === 200) {
						this.$message.success('修改分组成功！');
						this.showEditTips = false;
						this.initGroupList();
					}
				})
				.catch(err => {
					this.$Spin.hide();
					this.$requestApiError(err, () => {
						this.$router.push('/');
					});
				});
		},
		// 删除分组按钮方法
		deleteGroup(index, row) {
			this.$confirm(`确定要删除 ${row.groupName} 分组吗,是否继续？`, '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			})
				.then(() => {
					let data = {};
					data.id = row.groupId;
					deleteGroups(data)
						.then(res => {
							if (res.status === 200) {
								this.$message.success('删除分组成功！');
								this.initGroupList();
							}
						})
						.catch(err => {
							if (err.code === '1201') {
								this.$message({
									type: 'error',
									message: '删除失败！分组正在使用中！！！'
								});
							}
						});
				})
				.catch(() => {
					this.$message({
						type: 'info',
						message: '已取消'
					});
				});
		},
		// 修改自定义属性
		changeProp(val, index) {
			this.addGropusData.customizedPolicy[index].rules = val;
		},
		// 分组管理列表分页
		changePageSize(val) {
			this.checkData.pageSize = val;
			this.initGroupList();
		},
		changeCurrentPage(val) {
			this.checkData.page = val;
			this.initGroupList();
		}
	}
};
</script>

<style lang="less" scoped>
.head {
	padding: 20px 0;
}
</style>
